// ActionScript file
import mx.core.UIComponent;
import com.helloniu.fl.widget.ByteArrayImage;
import com.helloniu.fl.util.Tool;
import flash.events.Event;
import flash.net.FileFilter;
import flash.net.FileReference;

private var fileReference:FileReference = null;
private var fileData:ByteArray;
private var img2:ByteArrayImage;

private var imgCon:UIComponent = null;
private var foregroundCom:UIComponent = null;

// open api
public function setImageContainer(aimgCon:UIComponent):void {
	this.imgCon = aimgCon;
}

public function setForegroundComponent(aforegroundCom:UIComponent):void {
	this.foregroundCom = aforegroundCom;
}

/// inner logic
private function unloadFile(event:Event):void  {
	imgCon.removeChild(img2);
	img2.dispatchEvent(new Event(Event.UNLOAD));
}

private function selectLocalFile(event:Event):void  {    
	fileReference = new FileReference();

    fileReference.browse([new FileFilter("*.jpg;*.txt;*.jpeg", "*.jpg;*.txt;*.jpeg")]);
    fileReference.addEventListener(Event.SELECT, selectOver, false,
                                   0, false);
}

private function selectOver(event:Event):void {
	filename.text = fileReference.name;
	startLoad();
}

public function startLoad():void {
    fileReference.addEventListener(Event.COMPLETE, loadOver, false,
                                   0, false);
    fileReference.addEventListener(IOErrorEvent.IO_ERROR, loadOver,
                                   false, 0, false);
    fileReference.addEventListener(SecurityErrorEvent.SECURITY_ERROR,
        loadOver, false, 0, false);

    // Load the file data to memory.
    fileReference.load();
}

private function loadOver(event:Event):void {
    fileReference.removeEventListener(Event.COMPLETE, loadOver);
    fileReference.removeEventListener(IOErrorEvent.IO_ERROR, loadOver);
    fileReference.removeEventListener(SecurityErrorEvent.SECURITY_ERROR, loadOver);

    if(event is IOErrorEvent || event is SecurityErrorEvent || 
        imgCon == null) 
    {
    	Tool.alert("==error found ");
    	return;
    }

    fileData = fileReference.data;
	img2 = new ByteArrayImage();
	img2.addEventListener(Event.COMPLETE, loadComplete);        
	img2.setData(fileData);        
	imgCon.addChild(img2);
	img2.validateNow();
}

private function loadComplete(event:Event):void {
	var img:ByteArrayImage = event.currentTarget as ByteArrayImage;
    
	if(img == null) {
    	return;
    }    

	var w:Number = img.width;
	var h:Number = img.height;
	imgCon.width = w;
	imgCon.height = h;

	if(foregroundCom != null) {
    	foregroundCom.width = w;
    	foregroundCom.height = h;
    }
}